package cn.shenlong.portal.service.impl;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.shenlong.common.Pagination;
import cn.shenlong.portal.domain.Channel;
import cn.shenlong.portal.mapper.ChannelMapper;
import cn.shenlong.portal.service.ChannelService;
import cn.shenlong.portal.service.ContentService;
import cn.shenlong.util.UploadUtil;
import cn.shenlong.web.ThreadVariable;

@Service("channelService")
public class ChannelServiceImpl implements ChannelService {

	@Autowired
	private ChannelMapper channelMapper;

	@Autowired
	private ContentService contentService;

	@Override
	public int saveEntity(Channel entity) {
		return channelMapper.saveEntity(entity);
	}

	@Override
	public int updateEntity(Channel entity) {
		return channelMapper.updateEntity(entity);
	}

	@Override
	public Channel findByPK(Serializable entityId) {
		if (entityId != null) {
			return channelMapper.findByPK(entityId);
		} else {
			return null;
		}
	}

	@Override
	@Transactional
	public int deleteByPKArray(Serializable[] ids) {
		if (ids != null && ids.length > 0) {
			for (Serializable channelId : ids) {
				contentService.deleteContentByChannelId((Long) channelId);
				Channel channel = channelMapper.findByPK((Long) channelId);
				if (channel != null) {
					// 删除图片
					UploadUtil.deleteImgForHtml(channel.getTxt());
				}
			}
			channelMapper.deleteByPKArray(ids);
			return 0;
		} else {
			return 1;
		}
	}

	@Override
	public Pagination findPageListByCriteria(Integer pageNo, Integer pageSize,
			Map<String, Object> para) {
		RowBounds rowBounds = new RowBounds();
		if (pageNo != null && pageSize != null) {
			rowBounds = new RowBounds((pageNo - 1) * pageSize, pageSize);
		}
		Long count = channelMapper.findCountByCriteria(para);

		List<Channel> list = channelMapper.findPageListByCriteria(para,
				rowBounds);
		Pagination page = new Pagination(pageNo, pageSize, count.intValue(),
				list);
		return page;
	}

	@Override
	public List<Channel> getList() {
		List<Channel> list = channelMapper.getList();
		return list;
	}

	@Override
	public List<Channel> getListByParentId(Long parentId, boolean isContain) {
		if (isContain) {
			return channelMapper.getChildListByChannelId(parentId);
		} else {
			return channelMapper.getChildListByParentId(parentId);
		}
	}
}
